package com.twu.biblioteca;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class FindABook implements Options {
    private final ArrayList<String> iterms = new ArrayList<String>();
    private final ArrayList<String> books = new ArrayList<String>();
    private final ArrayList<String> availbleBooks = new ArrayList<String>();
    private static final String DON_T_MAKE_ME_THINK = "Don't Make Me Think";
    private static final String HEAD_FIRST_JAVA = "Head First Java";
    public int selectedOption = 0;

    public FindABook() {

        books.add(DON_T_MAKE_ME_THINK);
        books.add(HEAD_FIRST_JAVA);
        availbleBooks.add(DON_T_MAKE_ME_THINK);
        iterms.add("==== Find A Book ====");
        for (int i = 0; i < books.size(); i++) {
            iterms.add(books.get(i));
        }
    }

    @Override
    public void printOptions() {
        System.out.println(iterms.get(0));
        for (int i = 1; i < iterms.size(); i++) {
            System.out.println("  " + i + ". " + iterms.get(i));
        }
    }

    @Override
    public void setSelectedOption(int selectedOption) {
        this.selectedOption = optionsValidation(selectedOption);
    }

    @Override
    public int getSelectedOptionFromInput() {
        int index = 0;
        System.out.print("\nInput the Index of the option on menu please:");
        String input = getInput();
        try {
            index = Integer.parseInt(input);
        } catch (NumberFormatException e) {
            index = getSelectedOptionFromInput();
        }
        return index;
    }


    @Override
    public Options goToSelectedOption() {
        reserveABook();
        System.out.println("\nBack to Menu\n");
        Menu menu = new Menu();
        menu.printOptions();
        return menu;
    }

    public void reserveABook() {
        if (booksValidation(selectedOption)) {
            System.out.println("\nThank You! Enjoy the book.");
        }
    }


    private int optionsValidation(int selectedOption) {
        int validSelectedOption = selectedOption;
        while (validSelectedOption < 1 || validSelectedOption >= iterms.size()) {
            System.out.println("\nSelect a valid option!!");
            validSelectedOption = optionsValidation(getSelectedOptionFromInput());
        }
        return validSelectedOption;
    }

    private boolean booksValidation(int selectedOption) {
        if (availbleBooks.contains(iterms.get(selectedOption))) {
            return true;
        } else {
            System.out.println("\nSorry we don't have that book yet.");
            return false;
        }
    }

    private static String getInput() {
        try {
            BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
            return bufferRead.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
